<template>
  <div class="profile-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>个人信息</span>
      </div>
      <el-form ref="form" :model="userInfo" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="name">
              <el-input v-model="userInfo.name" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="mobile">
              <el-input v-model="userInfo.mobile"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userInfo.email"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="handleUpdate">保存修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Profile',
  data() {
    return {
      userInfo: {
        id: '',
        name: '',
        email: '',
        mobile: '',
        avatar: ''
      },
      rules: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  created() {
    this.getUserInfo()
  },
  methods: {
    getUserInfo() {
      const username = sessionStorage.getItem('user')
      this.$api.user.findByName({ 'name': username }).then(res => {
        if (res.code === 200) {
          this.userInfo = res.data
        }
      })
    },
    handleUpdate() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.$api.user.updateProfile(this.userInfo).then(res => {
            if (res.code === 200) {
              this.$message.success('个人信息修改成功')
            } else {
              this.$message.error(res.msg || '修改失败')
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.profile-container {
  padding: 20px;
}
.box-card {
  margin-bottom: 20px;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
</style> 